Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode rotateRight(ListNode head, int k) {
  11. if (head == null) {
  12. return null;
  13. }
  14. int len = getLength(head);
  15. k %= len;
  16. if (k == 0) {
  17. return head;
  18. }
  19. ListNode fast = head;
  20. ListNode slow = head;
  21. while (fast != null && k > 0) {
  22. fast = fast.next;
  23. k--;
  24. }
  25. while (fast.next != null) {
  26. slow = slow.next;
  27. fast = fast.next;
  28. }
  29. fast.next = head;
  30. head = slow.next;
  31. slow.next = null;
  32. return head;
  33. }
  34. int getLength(ListNode head) {
  35. int len = 0;
  36. while (head != null) {
  37. head = head.next;
  38. len++;
  39. }
  40. return len;
  41. }
  42. }